document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            // e.preventDefault();
            // 移除所有导航链接的激活状态
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            // 移除所有内容区域的激活状态
            contentAreas.forEach(content => content.classList.remove('active'));
            // 为当前点击的导航链接添加激活状态
            this.classList.add('active');
            // 获取目标内容区域的 ID
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                // 为目标内容区域添加激活状态
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    tables.forEach(function (table) {
        const selectAll = table.querySelector('.selectAll');
        const rowCheckboxes = table.querySelectorAll('.rowCheckbox');

        selectAll.addEventListener('change', function () {
            const isChecked = this.checked;
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });

        rowCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(rowCheckboxes).every(function (cb) {
                    return cb.checked;
                });
                selectAll.checked = allChecked;
            });
        });
    });
    //分页
    $(document).ready(function () {
        const rowsPerPage = 4; // 每页显示的行数
        const $tableBody = $('#table-body');
        const rows = $tableBody.find('tr');
        const numPages = Math.max(1, Math.ceil(rows.length / rowsPerPage));
        let currentPage = 1;

        // 显示指定页的数据
        function showPage(pageNumber) {
            currentPage = pageNumber;
            const startIndex = (pageNumber - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;

            // 隐藏所有行，然后显示当前页的行
            rows.hide();
            rows.slice(startIndex, endIndex).show();

            // 更新分页导航
            updatePagination();
        }

        // 更新分页导航
        function updatePagination() {
            const $pageNav = $('#pageNav');
            $pageNav.empty();

            // 添加"上一页"按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
                $prevBtn.addClass('disabled');
            } else {
                $prevBtn.click(function (e) {
                    e.preventDefault();
                    showPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 添加页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = startPage + maxVisiblePages - 1;

            if (endPage > numPages) {
                endPage = numPages;
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            // 添加省略号（如果需要）
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active');
                } else {
                    $pageBtn.click(function (e) {
                        e.preventDefault();
                        showPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 添加省略号（如果需要）
            if (endPage < numPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 添加"下一页"按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === numPages) {
                $nextBtn.addClass('disabled');
            } else {
                $nextBtn.click(function (e) {
                    e.preventDefault();
                    showPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }

        // 初始化页面
        if (rows.length > 0) {
            showPage(1);
        }
    });
    //禁言按钮
        // 禁言按钮逻辑
        const statusButtons = document.querySelectorAll('.static');
        statusButtons.forEach(function(button) {
            // 从HTML获取初始状态
            const initialStatus = button.textContent.trim();
            let isBanned = initialStatus === '禁言';
            // 初始化按钮样式
            updateButtonStyle(button, isBanned);
            button.addEventListener('click', function() {
                const userId = this.closest('tr').dataset.userId;
                const action = isBanned ? '解禁' : '禁言';
                const apiUrl = isBanned
                    ? `/admin/unMuteUser?id=${userId}`
                    : `/admin/muteUser?id=${userId}`;

                if (confirm(`确定要${action}这个用户吗？`)) {
                    // 发送AJAX请求
                    $.ajax({
                        url: apiUrl,
                        type: 'GET',
                        success: function(response) {
                            console.log(18)
                            // 更新UI状态
                            isBanned = !isBanned;
                            updateButtonStyle(button, isBanned);
                           Alert(`${action}成功`);
                        },
                        error: function(error) {
                            console.error('AJAX请求失败:', error);
                            Alert(`${action}失败，请稍后再试`);
                        }
                    });
                }
            });

        // 更新按钮样式的辅助函数
        function updateButtonStyle(button, isBanned) {
            button.textContent = isBanned ? '禁言' : '正常';
            button.style.backgroundColor = isBanned ? 'red' : '#49cc90';
        }
    });
//查询
        $('#check-button').click(function() {
            const searchTerm = $('#search').val();
            if (searchTerm.trim()!== '') {
                // 发送AJAX请求
                $.ajax({
                    type: 'GET',
                    url: '/admin/behind-manager-user', // 后端查询用户的API
                    data: { query: searchTerm },
                    success: function(response) {
                        // 清空表格
                        $('#table-body').empty();

                        // 填充表格
                        response.forEach(function(user) {
                            const row = $('<tr>')
                                .data('user-id', user.id)
                                .append(`<td><input type="checkbox" class="rowCheckbox"></td>`)
                                .append(`<td><img alt="" src="${user.avatar}"></td>`)
                                .append(`<td>${user.username}</td>`)
                                .append(`<td>${user.createdAt}</td>`)
                                .append(`<td>${user.email}</td>`)
                                .append(`<td>${user.gender}</td>`)
                                .append(`<td><button class="static">${user.status}</button></td>`)
                                .append(`<td>
                                                <button class="deletebtn" data-user-id="${user.id}">删除</button>
                                                <button class="editbtn nameedit" data-user-id="${user.id}">编辑</button>
                                            </td>`);
                            $('#table-body').append(row);
                        });
                    },
                    error: function(error) {
                        console.error('查询失败', error);
                        Alert('查询失败，请稍后重试');
                    }
                });
            } else {
                 Alert('请输入查询关键词');
            }
        });
//删除用户
    $(document).ready(function () {
        $('.deletebtn').click(function (event) {
            event.preventDefault();
            const userId = $(this).closest('tr').data('user-id');
            const $button = $(this); // 保存当前按钮的引用
           if(confirm('确定要删除该用户吗？')){
                $.ajax({
                    url: `http://localhost:8080/admin/toDeleteUser`,
                    method: 'GET',
                    // 添加data参数
                    data: { id: userId },
                    // 指定返回类型
                    dataType: 'text',
                    success: function (response) {
                        $button.closest('tr').remove();
                        console.log(userId);
                    },
                    error: function (error) {
                        console.log('删除用户失败:', error);
                         Alert('删除用户失败，请重试');
                        console.log(this.url);
                    }
                });
            }

        });

    });
    //添加
    //上传头像
    const fileInput = document.getElementById('fileInput');
    const avatarImg = document.getElementById('uimgs');
    // 处理文件选择
    fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            const validImageTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!validImageTypes.includes(file.type)) {
                 Alert('请选择JPG、PNG或GIF格式的图片');
                return;
            }

            // 使用FileReader读取文件并更新图片
            const reader = new FileReader();
            reader.onload = function(event) {
                avatarImg.src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    const addbtn = document.querySelector(' .add-button');
    const addModal = document.getElementById('addModal1');
    const cancel = document.querySelector(' .cancelEditPost1');
    const confirms = document.getElementById('userEditModalSaveButton1');
    cancel.addEventListener('click', function () {
        addModal.style.display = 'none';
        const  gender = document.getElementById("userGender").value;
        document.getElementById('userNamePostTitle').value = '';
        document.getElementById('userRegisterTime').value = '';
        document.getElementById('userEmail').value = '';
        document.getElementById('userPassword').value= '';
        document.getElementById("userGender").value= '';
        avatarImg.src = '';
    });
    addbtn.addEventListener('click', function () {
        addModal.style.display = 'block';
    });

    confirms.addEventListener('click', function () {
        const newimg = document.getElementById("uimgs").src;
        const  gender = document.getElementById("userGender").value;
        const  name = document.getElementById("userNamePostTitle1").value;
        const registerTime = document.getElementById("userRegisterTime1").value;
        const email = document.getElementById("userEmail1").value;
        const password = document.getElementById('userPassword').value;

        // 标签过滤
        const filteredName = name.replace(/<[^>]*>/g, '');
        const filteredRegisterTime = registerTime.replace(/<[^>]*>/g, '');
        const filteredEmail = email.replace(/<[^>]*>/g, '');

        if (validateInput(name, registerTime, email)) {
            var params = $.param({
                username: name,
                createAt: filteredRegisterTime,
                email: filteredEmail,
                bio: 'unknown',
                industry: 'unknown',
                location: 'unknown',
                shortBio: 'unknown',
                password: password,
                avatar: newimg,
                gender: gender
            });
            console.log(21);
            $.ajax({
                type: 'POST',
                url: `http://localhost:8080/admin/toAddUser`,
                data: params, // 修改为对象形式
                success: function (result) {
                    console.log(25);
                         Alert('确定添加？');
                        addModal.style.display = 'none';
                },
                error: function (result) {
                    addModal.style.display = 'none';
                    document.getElementById('userNamePostTitle1').value = '';
                    document.getElementById('userRegisterTime1').value = '';
                    document.getElementById('userEmail1').value = '';
                    document.getElementById('userPassword').value = '';
                    document.getElementById("userGender").value = '';
                    avatarImg.src = '';
                    console.log(result);
                    // 显示失败提示
                    addModal.style.display = 'none';
                     Alert('该用户添加失败', 3000);
                }
            });
        }
    });

    function validateInput(name, registerTime, email) {
        let isValid = true;
        const nameError = document.getElementById('nameError');
        const password = document.getElementById('userPassword').value;
        const timeError = document.getElementById('timeError');
        const emailError = document.getElementById('emailError');
        const passwordError = document.getElementById('passwordError');
        if (name === '') {
            nameError.textContent = '昵称不能为空';
            isValid = false;
        }
        if (registerTime === '') {
            timeError.textContent = '注册时间不能为空';
            isValid = false;
        } else if (!/^\d{4}-\d{2}-\d{2}$/.test(registerTime)) {
            timeError.textContent = '请输入正确的日期格式 (YYYY-MM-DD)';
            isValid = false;
        }
        if (email === '') {
            emailError.textContent = '邮箱不能为空';
            isValid = false;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            emailError.textContent = '请输入有效的邮箱地址';
            isValid = false;
        }
        if (!password) {
            passwordError.textContent = '密码不能为空';
            isValid = false;
        } else {
            const MIN_LENGTH = 8;
            const MAX_LENGTH = 20;
            const COMPLEXITY_REGEX = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
            if (password.length < MIN_LENGTH) {
                passwordError.textContent = `密码长度不能少于${MIN_LENGTH}个字符`;
                isValid = false;
            } else if (password.length > MAX_LENGTH) {
                passwordError.textContent = `密码长度不能超过${MAX_LENGTH}个字符`;
                isValid = false;
            } else if (!COMPLEXITY_REGEX.test(password)) {
                passwordError.textContent = '密码必须包含大小写字母、数字和特殊字符';
                isValid = false;
            }
            return isValid;
        }


        //弹窗
        function Alert(message, duration) {
            const alertDiv = document.createElement('div');
            alertDiv.style.position = 'fixed';
            alertDiv.style.top = '12px';
            alertDiv.style.right = '499px';
            alertDiv.style.backgroundColor = '#333';
            alertDiv.style.color = 'white';
            alertDiv.style.padding = '10px';
            alertDiv.style.borderRadius = '5px';
            alertDiv.style.boxShadow = '0 0 5px rgba(0, 0, 0, 0.3)';
            alertDiv.style.zIndex = '1000';
            alertDiv.style.opacity = '0';
            alertDiv.style.width = '300px';
            alertDiv.style.textAlign = 'center';
            alertDiv.style.transition = 'opacity 0.3s ease-in-out';
            alertDiv.textContent = message;

            document.body.appendChild(alertDiv);

            alertDiv.style.opacity = '1';

            setTimeout(() => {
                alertDiv.style.opacity = '0';
                setTimeout(() => {
                    document.body.removeChild(alertDiv);
                }, 3000);
            }, duration);
        }
    }
    //获取编辑id信息
    document.getElementById('avatarUpload').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('newimg').src = e.target.result;
                document.getElementById('newimg').style.display = 'block';
            }
            reader.readAsDataURL(file);
        }
    });
        const userEditModal=document.getElementById('userEditModal')
        const editButtons = document.querySelectorAll('.editbtn');
        editButtons.forEach(button => {
            button.addEventListener('click', function() {
                // 检查this是否指向正确的DOM元素
                console.log('this:', this);

                // 使用dataset获取用户ID
                const userId = this.dataset.userId;
                console.log('userId:', userId);
                // 获取当前点击按钮的用户ID
                userEditModal.style.display = 'block';
                console.log('编辑用户ID:', userId); // 用于调试

                if (!userId) {
                    Alert('无效的用户ID');
                    return;
                }
                const url = `http://localhost:8080/admin/toUpdateUserPage?id=${userId}`;
                // 使用AJAX获取用户数据
                $.ajax({
                    dataType: 'json', // 明确指定返回JSON格式
                    url:url,
                    method: 'GET',
                    success: function(user) {
                        console.log('获取用户数据成功:', user); // 用于调试
                        // 填充表单数据
                        document.getElementById('userNamePostTitle').value =user.user.username;
                        document.getElementById('userRegisterTime').value = user.user.createdAt;
                        document.getElementById('userEmail').value =  user.user.email;
                        document.getElementById('userAddress').value =  user.user.location;
                        document.getElementById('userGenders').value =  user.user.gender;
                        document.getElementById('userIndustry').value =  user.user.industry;
                        document.getElementById('userBriefIntro').value =  user.user.shortBio;
                        document.getElementById('userIntroduction').value =  user.user.bio;
                        document.getElementById('passwordPostTitle').value =  user.user.password;
                        document.getElementById('newimg').src=  user.user.avatar;
                        // 保存用户ID到保存按钮的dataset中
                        document.getElementById('userEditModalSaveButton').dataset.userId = userId;
                        // 显示编辑模态框
                        document.getElementById('userEditModal').style.display = 'block';
                    },
                    error: function(error) {
                        console.error('请求出错:', error);
                        Alert('请求出错，请稍后重试');
                    }
                });
            });
        });

        // 保存按钮的点击事件
        document.getElementById('userEditModalSaveButton').addEventListener('click', function(e) {
            e.preventDefault();

            // 从保存按钮的dataset中获取用户ID
            // 获取用户ID
            const id = document.getElementById('userEditModalSaveButton').dataset.userId;
            console.log('保存用户ID:', id);

// 获取表单数据
            const password = document.getElementById('passwordPostTitle').value;
            const name = document.getElementById('userNamePostTitle').value;
            const email = document.getElementById('userEmail').value;
            const location = document.getElementById('userAddress').value;
            const gender = document.getElementById('userGenders').value;
            const industry = document.getElementById('userIndustry').value;
            const shortBio = document.getElementById('userBriefIntro').value;
            const bio = document.getElementById('userIntroduction').value;
            const img = document.getElementById('newimg').src;

// 验证必要字段
            if (!password || !name || !email) {
                 Alert('用户名、密码和邮箱不能为空');
                return;
            }

            const urlParams = new URLSearchParams({
                id: id,
                username: name,
                password: password,
                email: email,
                avatar: img,
                gender: gender,
                location: location,
                industry: industry,
                shortBio: shortBio,
                bio: bio,
                // 移除createdAt，因为注册时间通常不应该被修改
                // createdAt: registerTime
            }).toString();

            console.log('更新用户参数:', urlParams);

            $.ajax({
                url: `http://localhost:8080/admin/toUpdateUser?${urlParams}`,
                method: 'POST',
                success: function(response) {
                    console.log('保存结果:', response); // 用于调试
                         Alert('编辑成功');
                        document.getElementById('userEditModal').style.display = 'none';
                        // 刷新表格数据
                        window.location.reload();
                },
                error: function(error) {
                    console.error('请求出错:', error);
                     Alert('请求出错，请稍后重试');
                }
            });
        });

        // 取消按钮的点击事件
        document.querySelector('.cancelEditPost1').addEventListener('click', function() {
            document.getElementById('userEditModal').style.display = 'none';
        });

});